<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
  >
    <h2>添加任务</h2>
    <el-form-item
      label="任务名称"
      prop="newTask"
    >
      <el-input
        v-model="form.newTask"
        placeholder="输入任务名称"
      />
    </el-form-item>
    <el-form-item>
      <el-button @click="startSpeechRecognition">
        <svg
          v-if="isListening"
          xmlns="http://www.w3.org/2000/svg"
          width="20"
          height="20"
          viewBox="0 0 20 20"
          fill="currentColor"
        >
          <circle cx="10" cy="10" r="8" fill="transparent" stroke="currentColor" stroke-width="2">
            <animate
              attributeName="r"
              from="6"
              to="8"
              dur="1s"
              repeatCount="indefinite"
            />
          </circle>
        </svg>
        语音输入
      </el-button>
    </el-form-item>
    <el-form-item>
      <el-checkbox v-model="form.isCompleted">
        已完成
      </el-checkbox>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        @click="submitTask"
      >
        添加
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { ref } from 'vue'
import { useStore } from 'vuex'

export default {
  setup() {
    const formRef = ref(null)
    const form = ref({
      newTask: '',
      isCompleted: false
    })

    const isListening = ref(false) // 添加 isListening 状态

    const rules = {
      newTask: [
        { required: true, message: '任务名称不能为空', trigger: 'blur' }
      ]
    }

    const store = useStore()

    const submitTask = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          store.dispatch('addTask', { name: form.value.newTask, completed: form.value.isCompleted })
          form.value.newTask = ''
          form.value.isCompleted = false
        } else {
          console.log('表单验证失败!')
          return false
        }
      })
    }

    const startSpeechRecognition = () => {
      const recognition = new window.webkitSpeechRecognition()
      recognition.lang = 'zh-CN'

      recognition.onaudiostart = () => {
        isListening.value = true // 开始监听时显示动画
      }

      recognition.onresult = (event) => {
        const transcript = event.results[0][0].transcript
        form.value.newTask = transcript
      }

      recognition.onend = () => {
        isListening.value = false // 结束监听时隐藏动画
        console.log('语音识别结束')
      }

      recognition.start()
    }

    return {
      form,
      rules,
      formRef,
      submitTask,
      startSpeechRecognition,
      isListening
    }
  }
}
</script>
